package cgs_worksheet

import (
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"cgs-server/helper"
	"cgs-server/server"
	"net/http"
	"strings"
)

func init() {
	//server.Handle(http.MethodGet, "/api/Cgs/PreviewExcel", PreviewExcel, server.ImportExcel)
	server.Get("/api/Cgs/PreviewExcel", PreviewExcel, "预览excel数据", server.Login)
}

// PreviewExcel 预览 excel，返回每个视图的前 10 行数据
func PreviewExcel(w http.ResponseWriter, r *http.Request) {
	_ = r.ParseForm()

	// 权限
	if server.Config.Authority.Enabled {
		user, _ := server.GetCurrentUser(r)

		if user == nil {
			_, _ = helper.WriteJSON(w, server.CgsResult{
				Code: 300,
				Msg:  "Permission denied.",
			})
			return
		}

	}

	filePath := strings.TrimSpace(r.FormValue("filePath"))
	if filePath == "" {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  "Filepath is required!",
		})
		return
	}

	resp, err := http.Get(filePath)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	if resp.StatusCode != 200 {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  fmt.Sprintf("http status: %v %v", resp.StatusCode, resp.Status),
		})
		return
	}
	defer resp.Body.Close()

	f, err := excelize.OpenReader(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}

	// 获取 Sheet1 上第一行的单元格
	rows, err := f.GetRows("Sheet1")
	if len(rows) == 0 {
		_, _ = helper.WriteJSON(w, server.CgsResult{
			Code: 300,
			Msg:  "Sheet1 can not be empty.",
		})
		return
	}

	row := rows[0]
	cells := []Cell{}
	for index, colCell := range row {
		//fmt.Print(colCell, "\t")
		cell := Cell{
			ColumnNumber: index,
			Value: colCell,
		}
		cells = append(cells, cell)
	}
	rowsData := Row{
		Cells: cells,
		RowNumber: 0,
	}

	_, _ = helper.WriteJSON(w, server.CgsResult{
		Code: 200,
		Msg:  "Get successfully!",
		Data: []Row{rowsData},
	})
}


type Row struct {
	// 单元格信息
	Cells 		[]Cell	`json:"cells" bson:"cells"`
	// 行号
	RowNumber	int	`json:"rowNumber" bson:"rowNumber"`
}

type Cell struct {
	// 列号
	ColumnNumber	int		`json:"columnNumber" bson:"columnNumber"`
	// 值
	Value			string 		`json:"value" bson:"value"`
}
